package app

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
)

/**
 * Created with IntelliJ IDEA.
 * User: 令狐飞侠
 * Date: 2021-11-30
 * Description: gin 中间件
 */
func TestSimpleMiddleware() {
	router := gin.Default()
	// 登录
	router.GET("/login", func(context *gin.Context) {
		//保存cookie
		cookie := &http.Cookie{
			Name:     "user",
			Value:    "admin",
			Path:     "/",
			HttpOnly: true,
		}
		http.SetCookie(context.Writer, cookie)

		context.JSON(200, gin.H{
			"message": "登录成功!",
		})
	})
	// 单个路由的中间件
	router.GET("/simple", MiddleWare(), func(context *gin.Context) {
		context.JSON(200, gin.H{
			"message": "单个路由的中间件!",
		})
	})
	//启动端口8080的服务
	router.Run(":8080")
}

// 群组路由的中间件
func TestGroupMiddleware() {
	groupRouter := gin.Default()
	// 群组路由的中间件
	userRouter := groupRouter.Group("/user")
	// 登录
	userRouter.GET("/login", func(context *gin.Context) {
		//保存cookie
		cookie := &http.Cookie{
			Name:     "user",
			Value:    "admin",
			Path:     "/",
			HttpOnly: true,
		}
		http.SetCookie(context.Writer, cookie)

		context.JSON(200, gin.H{
			"message": "登录成功!",
		})
	})
	userRouter.Use(MiddleWare())
	{
		userRouter.GET("/Create", func(context *gin.Context) {
			context.JSON(200, gin.H{
				"message": "已增加一个新的用户!",
			})
		})
		userRouter.GET("/Update", func(context *gin.Context) {
			context.JSON(200, gin.H{
				"message": "已更新用户的信息!",
			})
		})
	}

	//启动端口8080的服务
	groupRouter.Run(":8080")
}

// 全局中间件
func TestGloalMiddleware() {
	router := gin.Default()

	// 登录
	router.GET("/login", func(context *gin.Context) {
		//保存cookie
		cookie := &http.Cookie{
			Name:     "user",
			Value:    "admin",
			Path:     "/",
			HttpOnly: true,
		}
		http.SetCookie(context.Writer, cookie)

		context.JSON(200, gin.H{
			"message": "登录成功!",
		})
	})

	router.GET("/user", func(context *gin.Context) {
		context.JSON(200, gin.H{
			"message": "不受全局中间件的影响!",
		})
	})

	router.Use(MiddleWare())
	{
		router.GET("/shop", func(context *gin.Context) {
			context.JSON(200, gin.H{
				"message": "受全局中间件的影响!",
			})
		})
	}

	//启动端口8080的服务
	router.Run(":8080")
}

// 中间件实现鉴权认证
func MiddleWare() gin.HandlerFunc {
	return func(context *gin.Context) {
		cookie, err := context.Request.Cookie("user")
		if err == nil {
			value := cookie.Value
			fmt.Println("user:", value)
			if value == "admin" {
				context.Next()
				return
			}
		}
		context.JSON(
			http.StatusUnauthorized, gin.H{
				"message": "没有授权！",
			})

		context.Abort()
		return
	}
}
